import binascii

def read_and_write_hex(file_path,hex_string):
    try:
        hex_data = bytes.fromhex(hex_string)
        
        with open(file_path, 'wb') as file:
            file.write(hex_data)
            
    except Exception as e:
        print(f"写入文件时出现错误：{e}")

def unicode_to_hex(input_str):
    hex_str = ""
    for char in input_str:
        hex_str += format(ord(char), 'x') + " "
    return hex_str.strip()

def small_to_capital(input_str):
    c_char = ""
    for char in input_str:
        if "a" <= char <= "z" :
            c_char += chr(ord(char)-32)
        else:
            c_char += char
    return c_char

def convert(input_str):
    c_str = ""
    string_list = input_str.split()
    for char in string_list:
        c_char = char[2:4] + char[0:2]
        c_str += c_char
    return c_str

def read_txt(input_add,num):
    cut_txt = ""
    j,k = 0,0
    txt_list = []
    s = open(input_add,"r",encoding="UTF-8")
    all_txt = s.read()
    all_txt = all_txt.replace('\n', '')
    for i in all_txt:
        cut_txt += i
        if len(cut_txt) == num:
            txt_list.append(cut_txt)
            cut_txt = ""
    txt_list.append(cut_txt)
    return txt_list

def count_str(add):
    char = open(add,"r",encoding="UTF-8")
    char_1 = char.read()
    out = len(char_1)
    return out
    
def head(i,out):
    str_1 = ""
    if 255 >= i >= 15:
        str_1 = hex(i)[2:] + "00"
    elif i > 255:
        str_2 = "0" + hex(i)[2:]
        str_1 = str_2[2:4] + str_2[0:2]
    else:
        str_1 = "0" + hex(i)[2:] + "00"
        
    out_txt = "060101000100000028D7DE0002010100" + str_1 + out + "0000"
    return out_txt
out_add = "L0.hplist"
out_str = ""
input_add = input("拖入文本文件：")
num = input("设置单页字数：")
read_list = read_txt(input_add,num)
for char in read_list:
    out_str += convert(small_to_capital(unicode_to_hex(char)))
out_str = head(count_str(input_add),out_str)
#print("转换结果：", out_str)
read_and_write_hex(out_add,out_str)
print("已完成")